﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using C1.Phone.FlexGrid;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SMARTMobile.Common;
using SMARTMobile.Models;
using SMARTMobile.Utilities;
using SMARTMobile.ViewModels.Advance;
using SMARTMobile.WinPhone.Helpers;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace SMARTMobile.Views
{
    public partial class OutletNokiaMerchandisingPotentialView //: PhoneApplicationPage
    {
private int _currentRowPopUp;
        private int _currentIndex;
        private int _currentRowGrid;
        private int _imageQuantity;
        private string _currentImageName;
        private string currentCell;
        public OutletNokiaMerchandisingPotentialView()
        {
            InitializeComponent();
            OutletNokiaMerchandisingPotentialViewModel viewModel = new OutletNokiaMerchandisingPotentialViewModel();
            this.DataContext = viewModel;
        }
        
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string msg;
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
            {
                if (!string.IsNullOrEmpty(msg) && msg.Contains("ExplainMerchandising"))
                {
                    string tempName = msg.Split(';')[1];
                    currentCell = tempName;
                    _currentRowPopUp = int.Parse(tempName.Split(':')[1]);
                    _currentIndex = int.Parse(tempName.Split(':')[2]);
                    _imageQuantity = int.Parse(tempName.Split(':')[3]);

                    SaveImageAfterTakenMerchandising("Merchandising\\", "Merchandising");
                    this.ChupHinh.IsOpen = true;
                    this.LoadPopup();
                }
            }
        }

        private void SaveImageAfterTakenMerchandising(string prefix, string folder)
        {
            int row = int.Parse(currentCell.Split(':')[4]);
            _currentRowGrid = row;
            _currentImageName = prefix + this.FlexGrid[row, "Customerkey"] + "~" + this.FlexGrid[row, "MerchandisingCode"] + "~" + _currentRowPopUp.ToString() + ".jpeg";

            Utilities.ImageUtilities.SaveToJpeg(Utilities.ImageUtilities.GetLatestImage(), _currentImageName, folder);
        }

        private void NhapDuLieuPage_BeginningEdit(object sender, CellEditEventArgs e)
        {
            if ((sender as C1FlexGrid).Columns[e.Column].ColumnName == "WherePicture")
            {
                _currentRowGrid = e.Row;
                //if (string.IsNullOrEmpty((sender as C1FlexGrid)[e.Row, "Qty"].ToString()))
                //{
                //    MessageBox.Show("Chưa nhập số lượng");
                //    return;
                //}

                _imageQuantity = string.IsNullOrEmpty((sender as C1FlexGrid)[e.Row, "QtyPicture"].ToString()) ? 5 : int.Parse((sender as C1FlexGrid)[e.Row, "QtyPicture"].ToString());
                //_imageQuantity = 1;
                if (_imageQuantity > 0)
                {
                    this.ChupHinh.IsOpen = true;
                    // Todo: Get image taken from isolated
                    List<TakePictureModel> items = new List<TakePictureModel>();

                    string picture = (sender as C1FlexGrid)[e.Row, "WherePicture"].ToString();
                    if (picture != string.Empty && int.Parse(picture.Split('/')[0]) > 0)
                    {
                        for (int i = 0; i < _imageQuantity; i++)
                        {
                            string imageName = "Merchandising\\" + this.FlexGrid[e.Row, "Customerkey"] + "~" + this.FlexGrid[e.Row, "MerchandisingCode"] + "~" + i.ToString() + ".jpeg";

                            TakePictureModel item = new TakePictureModel();
                            item.PictureURL = "";
                            item.Index = i;
                            item.CaptureTime = DateTime.Now;
                            item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                            item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainOutDoor;
                            if (ImageUtilities.CheckFileExist(imageName))
                            {
                                item.PictureURL = imageName;
                                item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(imageName);
                            }

                            items.Add(item);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < _imageQuantity; i++)
                        {
                            TakePictureModel item = new TakePictureModel();
                            item.PictureURL = "";
                            item.Index = i;
                            item.CaptureTime = DateTime.Now;
                            item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                            item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainOutDoor;
                            item.PictureSource = new BitmapImage(new Uri(@"/Images/noimage.jpg", UriKind.RelativeOrAbsolute));
                            items.Add(item);
                        }
                    }

                    GlobalInformation.ListTakePictureModel = items;
                    listButton.ItemsSource = items;
                    //this.SavePreviousGrid();
                    GlobalInformation.CurrentColumnRowNhapDuLieu = e.Column.ToString() + ":" + e.Row.ToString();

                }

                _currentRowGrid = e.Row;
                e.Cancel = true;
            }
        }

        private void ExitModalWindow_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(GlobalInformation.CurrentColumnRowNhapDuLieu))
            {
                string[] item = GlobalInformation.CurrentColumnRowNhapDuLieu.Split(':');
                string value = GlobalInformation.ListTakePictureModel.Count(a => a.PictureURL != "").ToString() + "/" + GlobalInformation.ListTakePictureModel.Count().ToString();
                this.FlexGrid[int.Parse(item[1]), int.Parse(item[0])] = value;
                this.SavePreviousGrid();
            }

            this.ChupHinh.IsOpen = false;
        }

        private void SavePreviousGrid()
        {
            var vm = DataContext as OutletNokiaMerchandisingPotentialViewModel;
            
            vm.SaveData();
        }

        public void UpdateQuantityInput(string merchanCode, int qty)
        {
            var vm = DataContext as OutletNokiaMerchandisingPotentialViewModel;

            vm.UpdateData(merchanCode, qty);
        }
        
        private void LoadPopup()
        {
            if (_imageQuantity > 0)
            {
                this.ChupHinh.IsOpen = true;
                foreach (TakePictureModel item in GlobalInformation.ListTakePictureModel)
                {
                    if (item.Index == _currentRowPopUp)
                    {
                        item.PictureURL = _currentImageName;
                        item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(item.PictureURL);
                    }
                }

                listButton.ItemsSource = GlobalInformation.ListTakePictureModel;
            }
        }

        private void DuyetImageButton_OnTap(object sender, GestureEventArgs e)
        {
            if (e.OriginalSource is Image)
            {
                if ((e.OriginalSource as Image).Tag != null)
                {
                    TakePictureModel model = (e.OriginalSource as Image).Tag as TakePictureModel;
                    GlobalInformation.StateImageType = 0;
                    NavigationService.Navigate(new Uri("/Views/ChupHinhCuaHangPage.xaml?msg=" + "Merchandising;" + "0" + ":" + model.Index.ToString() + ":" + _currentIndex.ToString() + ":" + _imageQuantity.ToString() + ":" + _currentRowGrid.ToString(), UriKind.Relative));
                }
            }
        }

        private void FlexGrid_OnCellEditEnded(object sender, CellEditEventArgs e)
        {
            if ((sender as C1FlexGrid).Columns[e.Column].ColumnName == "Qty" && this.FlexGrid[e.Row, "Qty"] != null)
            {
                int number;
                if (int.TryParse(this.FlexGrid[e.Row, "Qty"].ToString(), out number))
                {
                    this.UpdateQuantityInput(this.FlexGrid[e.Row, "MerchandisingCode"].ToString(), number);
                }
            }
        }
    }
}